import win32con
import win32gui
import win32process


def getHwndsByPID(target_pid):
    """通过 PID 找到目标进程的所有窗口句柄"""
    hwnd_list = []

    def enum_windows_callback(hwnd, pid):
        # 获取窗口所属的进程 PID
        window_pid = win32process.GetWindowThreadProcessId(hwnd)[1]
        if window_pid == pid:
            hwnd_list.append(hwnd)
        return True

    # 枚举所有顶层窗口
    win32gui.EnumWindows(enum_windows_callback, target_pid)
    return hwnd_list


# 添加一个可选的备用方法，通过枚举窗口并检查标题或其他属性
def getHwndsByClass_alt(value):
    """通过窗口标题或类名获取窗口句柄的备用方法"""
    hwnd_list = []
    
    def enum_callback(hwnd, target_value):
        try:
            # 获取窗口标题和类名
            title = win32gui.GetWindowText(hwnd)
            class_name = win32gui.GetClassName(hwnd)
            
            # 检查窗口是否可见
            if win32gui.IsWindowVisible(hwnd):
                # 检查标题或类名是否包含目标值
                if target_value in title or target_value in class_name:
                    print(f"找到匹配的窗口: {hwnd}, 标题: '{title}', 类名: '{class_name}'")
                    hwnd_list.append(hwnd)
            return True
        except Exception as e:
            print(f"枚举窗口时出错: {str(e)}")
            return True  # 继续枚举
    
    print(f"开始枚举所有窗口，查找包含 '{value}' 的标题或类名...")
    win32gui.EnumWindows(enum_callback, value)
    return hwnd_list


def showWindow(hwnd):
    """显示窗口"""
    win32gui.ShowWindow(hwnd, win32con.SW_SHOWNOACTIVATE)
    try:
        win32gui.SetForegroundWindow(hwnd)
    except Exception as e:
        print(f'设置窗口 {hwnd} 为前台窗口时出错: {str(e)}')
    print(f'窗口 {hwnd} 已显示')


def hideWindow(hwnd):
    """隐藏窗口"""
    win32gui.ShowWindow(hwnd, win32con.SW_HIDE)
    print(f'窗口 {hwnd} 已隐藏')


def minimizeWindow(hwnd):
    """最小化窗口"""
    win32gui.ShowWindow(hwnd, win32con.SW_MINIMIZE)
    print(f'窗口 {hwnd} 已最小化')


def restoreWindow(hwnd):
    """恢复窗口"""
    win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
    print(f'窗口 {hwnd} 已恢复')


def maximizeWindow(hwnd):
    """最大化窗口"""
    win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
    print(f'窗口 {hwnd} 已最大化')


def getWindowTitle(hwnd):
    """获取窗口标题"""
    return win32gui.GetWindowText(hwnd)
